package demo1.controller;

import demo1.entity.Blog;
import demo1.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin(origins = "http://localhost:5173")
@RestController
public class BlogController {
    @Autowired
    private BlogService blogService;
    //显示所有博客内容
//    @GetMapping("/api/blogs")
//    public List<Blog> getBlogs() {
//        List<Blog> blogs = new ArrayList<Blog>();
//        //调用Service获取所有博客的内容
//        return blogService.findAll();
//    }
    //分页显示博客内容，通过offset limit来进行选择性查询
    //处理分页参数，通过url传递分页信息（page和size），并且设置默认值
    @GetMapping("/api/blogs")
    public ResponseEntity getBlogsByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        //获取当前页面的数据
        List<Blog> blogs = blogService.findByPage( page,size);
        //获取总博客数量
        int total = blogService.count();
        //构建相应数据
        Map<String,Object> map = new HashMap<>();
        map.put("blogs",blogs);
        map.put("total",total);
        return ResponseEntity.ok(map);
    }
}
